package com.xncoding.trans.hannder;

import com.alibaba.fastjson.JSON;
import com.xncoding.trans.enums.RedisCacheEnums;
import com.xncoding.trans.service.RedisCacheUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
 * @CreateAt: 2023-11-3 11:30:30
 * @ModifyAt: 2023-11-3 11:30:30
 * @Version 1.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class MemberHandler implements RedisCacheHandler {
    private final String redisKey = "test";
    // 切换成自己项目使用的redis工具类即可
    @Resource
    private RedisCacheUtils resdisUtil;
    /**
     * 是否支持处理
     *
     * @param type
     * @return
     */
    public boolean support(RedisCacheEnums type) {
        return RedisCacheEnums.QUERY_MEMBER_INFO.equals(type);
    }
    /**
     * 查询缓存信息
     *
     * @param args
     * @param originalKey
     * @return
     */
    @Override
    public Object queryHandler(Object[] args, String originalKey) throws Exception {
        String key = getKey(args, originalKey);
        return resdisUtil.getCacheObject(key);
    }
    /**
     * 查询缓存信息
     *
     * @param args
     * @param originalKey
     * @return
     */
    @Override
    public Boolean existHandler(Object[] args, String originalKey) throws Exception {
        String key = getKey(args, originalKey);
        return resdisUtil.hasKey(key);
    }
    /**
     * 生成操作记录对象
     *
     * @param type
     * @param args
     * @param result
     * @param time
     * @param timeType
     * @param originalKey
     * @return
     */
    public void handler(RedisCacheEnums type, Object[] args, Object result, Integer time, TimeUnit timeType, String originalKey) throws Exception {
        String key = getKey(args, originalKey);
        resdisUtil.setCacheObject(key, result, Long.parseLong(String.valueOf(time)), timeType);
    }
    /**
     * 获取Key信息
     *
     * @param args
     * @return
     */
    private String getKey(Object[] args, String originalKey) throws Exception {
        try {
            Object omiMemberInquiryVO = (Object ) args[0];
            // 拼装缓存key信息
            String key = "test";
            System.out.println("RedisCacheAspect key:{}"+key);
            return key;
        } catch (Exception e) {
            System.out.println("RedisCacheAspect 拼装Key参数异常：{},e:{}"+JSON.toJSONString(args)+e.toString());
            throw new Exception("拼装Key参数异常");
        }
    }
}
